//package com.alibaba.cirtus.ots.application.app.ability.facade;
//
//import com.alibaba.cz.base.tool.log.Log;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.lattice2.epoch.sdk.model.Result;
//import com.epoch.app.bcots.model.dto.*;
//import com.epoch.app.bcots.model.dto.QueryCargoZoneByIdRequest;
//import com.epoch.app.bcots.model.dto.QueryCargoZoneByIdResponse;
//import com.epoch.app.bcots.service.BaseDataService;
//import com.epoch.app.bcots.service.PlatformEnhanceService;
//import com.epoch.app.bcots.service.UnifiedInventoryService;
//import com.epoch.app.otsapplicationappsdk.factorydelivery.dto.AsyncRequest;
//import com.epoch.app.otsapplicationappsdk.factorydelivery.dto.InitRequest;
//import com.epoch.app.otsapplicationappsdk.factorydelivery.dto.SubmitRequest;
//import com.epoch.app.otsapplicationappsdk.factorydelivery.service.FactoryDeliveryService;
//import com.epoch.app.otsforecastsales.api.forecastorderlinequery.service.ForecastOrderLineQueryService;
//import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.BatchQueryByIdsRequest;
//import com.epoch.app.otsplatformenhance.domain.customeraddress.model.CustomerAddress;
//import com.epoch.app.otsplatformenhance.domain.customeraddress.service.CustomerAddressService;
//import com.epoch.app.otsplatformenhance.goodsfavorites.dto.QueryGoodsFavoritesRequest;
//import com.epoch.app.otsplatformenhance.goodsfavorites.model.GoodsFavorites;
//import com.epoch.app.otsplatformenhance.goodsfavorites.service.GoodsFavoritesService;
//import com.epoch.app.otsunifiedinventory.api.allocateapplyorderdropdownselection.dto.QueryBranchCustomersRequest;
//import com.epoch.app.otsunifiedinventory.api.allocateapplyorderdropdownselection.service.AllocateApplyOrderDropDownSelectionService;
//import com.epoch.app.otsunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
//import com.epoch.app.otsunifiedinventory.api.allocateapplyorderwrite.service.AllocateApplyOrderWriteService;
//import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.dto.QueryDeliveryWarehouseByTypeRequest;
//import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.service.ForecastWarehouseService;
//import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderDetailDTO;
//import com.epoch.app.otsunifiedinventory.dto.response.DeliveryWarehouseChoiceDTO;
//import com.epoch.app.otsunifiedinventory.model.dto.*;
//import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderDetailCreateDTO;
//import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderUpdateDTO;
//import com.epoch.app.otsunifiedinventory.service.OtsUnifiedInventoryService;
//import com.google.common.collect.Lists;
//import lombok.Data;
//import org.apache.commons.collections.CollectionUtils;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import java.util.*;
//
//@Service
//public class FactoryDeliveryServiceImpl implements FactoryDeliveryService {
//
//    @Resource
//    BaseDataService baseDataService;
//
//    @Resource
//    ForecastWarehouseService forecastWarehouseService;
//
//    @Resource
//    ForecastOrderLineQueryService forecastOrderLineQueryService;
//
//    @Resource
//    OtsUnifiedInventoryService otsUnifiedInventoryService;
//
//    @Resource
//    PlatformEnhanceService platformEnhanceService;
//
//    @Resource
//    AllocateApplyOrderWriteService allocateApplyOrderWriteService;
//
//    @Resource
//    AllocateApplyOrderReadService allocateApplyOrderReadService;
//
//    @Resource
//    UnifiedInventoryService unifiedInventoryService;
//
//    @Resource
//    AllocateApplyOrderDropDownSelectionService allocateApplyOrderDropDownSelectionService;
//
//    @Resource
//    CustomerAddressService customerAddressService;
//
//    @Resource
//    private GoodsFavoritesService favoritesService;
//
//
//
//    private static Log log = Log.getLogger(FactoryDeliveryServiceImpl.class);
//
//    @Override
//    public Object init(InitRequest initRequest) {
//        log.info("创建工厂直发渲染页请求参数 {} " , JSON.toJSONString(initRequest));
//        JSONObject result = new JSONObject();
//        DataResult dataResult = new DataResult();
//        try {
//            //当前用户收藏夹货品
//            List goodsFavoritesList = new ArrayList();
//            try {
//                Result<List<GoodsFavorites>> listResult = favoritesService.queryGoodsFavorites(new QueryGoodsFavoritesRequest());
//                if (Objects.nonNull(listResult)&& CollectionUtils.isNotEmpty(listResult.getResult())){
//                    GoodsFavorites goodsFavorites = listResult.getResult().get(0);
//                    JSONArray goodsList = JSONArray.parseArray(goodsFavorites.getGoodsList());
//                    if (CollectionUtils.isNotEmpty(goodsList)) {
//                        for (Object goodsObj : goodsList) {
//                            JSONObject goodsJson = (JSONObject) JSONObject.toJSON(goodsObj);
//                            goodsFavoritesList.add(goodsJson.getString("goodsCode"));
//                        }
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//            //货品明细
//            try {
//                QueryGoodsListRequest queryGoodsListRequest = new QueryGoodsListRequest();
//                queryGoodsListRequest.setRecentlyUsedItemIdList(initRequest.getGoodsIdList());
//                if (CollectionUtils.isNotEmpty(goodsFavoritesList)) {
//                    queryGoodsListRequest.setGoodsFavoritesList(goodsFavoritesList);
//                }
//                Result<List<QueryGoodsListResponse>> queryGoodsListResponse = platformEnhanceService.queryGoodsList(queryGoodsListRequest);
//                dataResult.setScItemGoodsList(queryGoodsListResponse.getResult());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//            //单据类型  C端固定不单独调用API
//
//            try {
//                //提报组织
////                LoginEmployeeSubmissionOrganizationSelectResponse loginEmployeeSubmissionOrganizationSelectResponse = baseDataService.loginEmployeeSubmissionOrganizationSelect(new LoginEmployeeSubmissionOrganizationSelectRequest());
//                Result<List<AllocateOrganizationSelect>> loginEmployeeSubmissionOrganizationSelectResponse = allocateApplyOrderReadService.getCurrentEmployeeOrganizationSelect();
//                log.info("创建工厂直发渲染页 提报组织结果 {} ",JSONObject.toJSONString(loginEmployeeSubmissionOrganizationSelectResponse));
//                dataResult.setOrganizationSelectList(loginEmployeeSubmissionOrganizationSelectResponse.getResult());
//            } catch (Exception e) {
//                log.info("创建工厂直发渲染页 提报组织API异常");
//                e.printStackTrace();
//            }
//
//            try {
//                //发货仓
//                QueryDeliveryWarehouseByTypeRequest queryDeliveryWarehouseByTypeRequest = new QueryDeliveryWarehouseByTypeRequest();
//                queryDeliveryWarehouseByTypeRequest.setType("1");
//                Result<List<DeliveryWarehouseChoiceDTO>> deliveryWarehouseResult = new Result<>();
//                deliveryWarehouseResult = forecastWarehouseService.queryDeliveryWarehouseByType(queryDeliveryWarehouseByTypeRequest);
//                log.info("创建工厂直发渲染页 发货仓结果 {} ",JSONObject.toJSONString(deliveryWarehouseResult));
//                dataResult.setDeliveryWarehouseChoiceDTOList(deliveryWarehouseResult.getResult());
//            } catch (Exception e) {
//                log.info("创建工厂直发渲染页 发货仓API异常");
//                e.printStackTrace();
//            }
//
//
//            try {
//                //运输方式
//                Object transportModeMap = otsUnifiedInventoryService.transportModeReadServiceImplQueryTransportMode();
//                log.info("创建工厂直发渲染页 运输方式结果 {} ",JSONObject.toJSONString(transportModeMap));
//                JSONObject transportJson = (JSONObject)JSONObject.toJSON(transportModeMap);
//                dataResult.setTransportModeList(transportJson.get("result"));
//            } catch (Exception e) {
//                log.info("创建工厂直发渲染页 运输方式API异常");
//                e.printStackTrace();
//            }
//
//            try {
//                //货品组
//                GetScItemGroupSelectResponse scItemGroupSelect = baseDataService.getScItemGroupSelect();
//                dataResult.setScItemGroupSelect(scItemGroupSelect.getResult());
//            } catch (Exception e) {
//                log.info("创建工厂直发渲染页 货品组API异常");
//                e.printStackTrace();
//            }
//
//            try {
//                //分公司客户
//                Result<List<BranchCustomersDTO>> branchCustomers  = allocateApplyOrderDropDownSelectionService.queryBranchCustomers(new QueryBranchCustomersRequest());
//                log.info("创建工厂直发渲染页 分公司客户结果 {} ",JSONObject.toJSONString(branchCustomers));
//                if (branchCustomers != null) {
//                    dataResult.setBranchCustomersDTOS(branchCustomers.getResult());
//                }
//            } catch (Exception e) {
//                log.info("创建工厂直发渲染页 分公司客户API异常");
//                e.printStackTrace();
//            }
//
//
//            result.put("DataResult",dataResult);
//            result.put("success",true);
//        } catch (Exception e) {
//            log.info("创建工厂直发渲染页失败 {}",e.getMessage());
//            e.printStackTrace();
//            result.put("message","创建工厂直发渲染页失败");
//            result.put("success",false);
//        }
//        return result;
//    }
//
//    @Override
//    public Object async(AsyncRequest asyncRequest) {
//        log.info("工程直发异步 请求参数 {} " , JSON.toJSONString(asyncRequest));
//        JSONObject result = new JSONObject();
//        JSONObject updateFields = new JSONObject();
//        if (asyncRequest.getRequest() != null) {
//            JSONObject asyncParams = JSONObject.parseObject(JSON.toJSONString(asyncRequest.getRequest()));
//            if (asyncParams.get("fields") != null) {
//                JSONObject fieldsJson = asyncParams.getJSONObject("fields");
//                result = fieldsJson.getJSONObject("bizModel");
//                updateFields = fieldsJson.getJSONObject("updateFields");
//            }
//        }
//
//        if (updateFields.get("reportingOrganization") != null) {
//            //提报组织有变动
//        } else if (updateFields.get("warehouse") != null) {
//            //发货仓变动
//        }
//        log.info("工程直发异步返回结果 {} " , JSON.toJSONString(result));
//        return result;
//    }
//
//    @Override
//    public Object submit(SubmitRequest submitRequest) {
//        log.info("创建工厂直发提交 请求参数 {} " , JSON.toJSONString(submitRequest));
//        JSONObject result = new JSONObject();
//        try {
//        JSONObject request = (JSONObject)JSONObject.toJSON(submitRequest.getRequest());
//
//        JSONObject biModel = null;
//        String submitType = null;
//        JSONObject submitFields = null;
//        if (request != null && request.get("fields") != null) {
//            submitType  = request.getJSONObject("fields").getString("submitType");
//            submitFields = request.getJSONObject("fields").getJSONObject("submitFields");
//            biModel = request.getJSONObject("fields").getJSONObject("bizModel");
//        }
//
//        if (submitFields != null) {
//            Result<Boolean> submitResult = allocateApplyOrderSubmit(submitFields,submitType);
//            if (submitResult.isSuccess()) {
//                result.put("DataResult",biModel.getJSONObject("DataResult"));
//            } else {
//                result.put("success",false);
//                result.put("message",submitResult.getMessage());
//                return result;
//            }
//        }
//            if ("save".equals(submitType)) {
//                result.put("message","保存成功");
//            } else if ("submit".equals(submitType)) {
//                result.put("message","提交成功");
//            }
//        } catch (Exception e) {
//            log.info("创建工厂直发提交 异常 {} " , e.getMessage());
//        }
//
//
//        result.put("success",true);
//        return result;
//    }
//
//    public Result<Boolean> allocateApplyOrderSubmit(JSONObject submitFields, String submitType) {
//        Result<Boolean> result = new Result<>();
//        result.setSuccess(false);
//        Result<Boolean> checkResult = checkParams(submitFields,submitType);
//        if (!checkResult.isSuccess()) {
//            return checkResult;
//        }
//        try {
//            AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO = new AllocateApplyOrderCreateDTO();
//            allocateApplyOrderCreateDTO.setIsDTC(true);
//            //小程序创建标识
//            allocateApplyOrderCreateDTO.setIsAppCreate(true);
//            allocateApplyOrderCreateDTO.setApplyOrgId(submitFields.getLong("applyOrgId"));
//            allocateApplyOrderCreateDTO.setType(submitFields.getInteger("type"));
////            allocateApplyOrderCreateDTO.setCustomerAddress(submitFields.getString("customerAddress"));
////            allocateApplyOrderCreateDTO.setCustomer(submitFields.getString("customer"));
//            allocateApplyOrderCreateDTO.setShipWarehouseId(submitFields.getString("shipWarehouseId"));
//            allocateApplyOrderCreateDTO.setShipMethod(submitFields.getString("shipMethod"));
//            allocateApplyOrderCreateDTO.setRemark(submitFields.getString("remark"));
//            if (submitFields.getString("goodsGroup") != null) {
//                allocateApplyOrderCreateDTO.setGoodsGroup(Integer.valueOf(submitFields.getString("goodsGroup")));
//            }
//            if (submitFields.getString("branchCustomersCode") != null) {
//                allocateApplyOrderCreateDTO.setBranchCustomersCode(submitFields.getString("branchCustomersCode"));
//            }
//
//            if (submitFields.get("hopeDeliveryTime") != null) {
//                allocateApplyOrderCreateDTO.setHopeDeliveryTime(new Date(submitFields.getLong("hopeDeliveryTime")));
//            }
//            if (submitFields.getString("customerAddressId") != null) {
//                log.info("创建工厂直发 客户地址入参id "+ submitFields.getString("customerAddressId"));
//                BatchQueryByIdsRequest batchQueryByIdsRequest = new BatchQueryByIdsRequest();
//                batchQueryByIdsRequest.setIdList(Lists.newArrayList(submitFields.getString("customerAddressId")));
//                Result<List<CustomerAddress>> listResult = customerAddressService.batchQueryByIds(batchQueryByIdsRequest);
//                log.info("创建工厂直发提交 batchQueryByIds返回结果 {} " , JSON.toJSONString(listResult));
//                if(Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
//                    for (CustomerAddress customerAddress : listResult.getResult()) {
//                        allocateApplyOrderCreateDTO.setCustomerAddressId(submitFields.getString("customerAddressId"));
//                        allocateApplyOrderCreateDTO.setCustomer(customerAddress.getCustomerCode());
//                        allocateApplyOrderCreateDTO.setCustomerAddress(customerAddress.getAddressCode());
//                    }
//                }
//            }
//
//            log.info("创建工厂直发提交 调创建API参数 {} " , JSONObject.toJSONString(allocateApplyOrderCreateDTO));
//            Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderWriteService.createAllocateApplyOrder(allocateApplyOrderCreateDTO);
//
//            if (allocateApplyOrderDetailDTOResult.isSuccess()) {
//                AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
//                allocateApplyOrderUpdateDTO.setId(allocateApplyOrderDetailDTOResult.getResult().getId());
//                allocateApplyOrderUpdateDTO.setCode(allocateApplyOrderDetailDTOResult.getResult().getCode());
//                allocateApplyOrderUpdateDTO.setIsDTC(true);
//
//                List<AllocateApplyOrderDetailCreateDTO> list = new ArrayList<>();
//                if (submitFields.get("submitGoods") != null) {
//                    JSONArray jsonArray = submitFields.getJSONArray("submitGoods");
//                    if (CollectionUtils.isNotEmpty(jsonArray)) {
//                        for (Object goodsObj : jsonArray) {
//                            JSONObject goods = (JSONObject) JSONObject.toJSON(goodsObj);
//                            AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
//                            allocateApplyOrderDetailCreateDTO.setTitle(goods.getString("goodsName"));
//                            allocateApplyOrderDetailCreateDTO.setApplyQuantity(goods.getInteger("goodsNum"));
//                            allocateApplyOrderDetailCreateDTO.setGoodsId(goods.getString("id"));
//                            allocateApplyOrderDetailCreateDTO.setScItemId(goods.getString("goodsCode"));
//                            allocateApplyOrderDetailCreateDTO.setRemark(goods.getString("remark"));
//                            allocateApplyOrderDetailCreateDTO.setLineNo(goods.getInteger("goodsDetailsLine"));
//                            list.add(allocateApplyOrderDetailCreateDTO);
//                        }
//                    }
//                }
//                allocateApplyOrderUpdateDTO.setList(list);
//
//                log.info("请求创建工厂直发接口 入参 {} " , JSON.toJSONString(allocateApplyOrderUpdateDTO));
//
//                Result<Boolean> updateAllocateApplyOrderResult = null;
//                if ("submit".equals(submitType)) {
//                    updateAllocateApplyOrderResult =  allocateApplyOrderWriteService.submitAllocateApplyOrder(allocateApplyOrderUpdateDTO);
//                } else if ("save".equals(submitType)) {
//                    updateAllocateApplyOrderResult =  allocateApplyOrderWriteService.updateAllocateApplyOrder(allocateApplyOrderUpdateDTO);
//                }
//                if (!updateAllocateApplyOrderResult.isSuccess()) {
//                    result.setMessage(updateAllocateApplyOrderResult != null ? updateAllocateApplyOrderResult.getMessage() : "保存提交失败");
//                    return result;
//                }
//            } else {
//                result.setMessage(allocateApplyOrderDetailDTOResult.getMessage());
//                return result;
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.info("创建工厂直发提交 请求RPC异常 {} " , e.getMessage());
//            result.setMessage("保存提交失败");
//            return result;
//        }
//        result.setSuccess(true);
//        return result;
//    }
//
//    public Result<Boolean> checkParams(JSONObject submitFields, String submitType) {
//        Result<Boolean> result = new Result<>();
//        result.setSuccess(true);
//        if (submitFields.getLong("customerAddress") == null) {
//            result.setMessage("客户地址必填");
//            result.setSuccess(false);
//            return result;
//        }  else if (submitFields.getString("hopeDeliveryTime") == null) {
//            result.setMessage("期望发货日期必填");
//            result.setSuccess(false);
//            return result;
//        }
//        if (submitFields.get("submitGoods") == null || CollectionUtils.isEmpty(submitFields.getJSONArray("submitGoods"))) {
//            result.setMessage("货品明细不能为空");
//            result.setSuccess(false);
//            return result;
//        }
//
//        return result;
//    }
//
//    public List<QueryGoodsListResponse> buildGoodsList(List<QueryGoodsListResponse> queryGoodsList,List goodsIdList) {
//        if (CollectionUtils.isEmpty(goodsIdList)) {
//            return queryGoodsList;
//        }
//        if (CollectionUtils.isEmpty(queryGoodsList)) {
//            return queryGoodsList;
//        }
//        Set<String> goodsIdSet = new HashSet();
//        for (Object goodsId : goodsIdList) {
//            goodsIdSet.add(goodsId.toString());
//        }
//        List list = new ArrayList();
//        for (String goodsId : goodsIdSet) {
//            boolean flg = false;
//            for (QueryGoodsListResponse queryGoodsListResponse : queryGoodsList) {
//                flg = false;
//                if (CollectionUtils.isNotEmpty(queryGoodsListResponse.getGoodsList())) {
//                    for (Object goodsObj : queryGoodsListResponse.getGoodsList()) {
//                        JSONObject goodsJson = (JSONObject) JSONObject.toJSON(goodsObj);
//                        if (goodsId.equals(goodsJson.getString("id"))) {
//                            list.add(goodsObj);
//                            flg = true;
//                            break;
//                        }
//                    }
//                }
//                if (flg) break;
//            }
//        }
//        if (CollectionUtils.isEmpty(list)) {
//            return queryGoodsList;
//        }
//        QueryGoodsListResponse queryGoodsListResponse = new QueryGoodsListResponse();
//        //端上构造的虚假常用货品类目,库中无该类目
//        queryGoodsListResponse.setLabel("常用货品");
//        queryGoodsListResponse.setGoodsList(list);
//
//        List<QueryGoodsListResponse> queryGoodsListResponseList = new ArrayList<>();
//        queryGoodsListResponseList.add(queryGoodsListResponse);
//        queryGoodsListResponseList.addAll(queryGoodsList);
//
//        return queryGoodsListResponseList;
//    }
//
//
//    @Data
//    public class DataResult {
//        private List scItemGoodsList;
//        private List OrganizationSelectList;
//        private List<DeliveryWarehouseChoiceDTO> deliveryWarehouseChoiceDTOList;
//        private Object transportModeList;
//        private List<BranchCustomersDTO> branchCustomersDTOS;
//        private List scItemGroupSelect;
//        private Map<String,Object> feature;
//    }
//
//}
